package org.zzh.service.common;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.zzh.domain.company.SsCompany;
import org.zzh.domain.system.dept.PeDept;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CommonService {

    public void setCompanyDetails(PeDept dept, HttpSession session) {
        if (session.getAttribute("company") == null) {
            dept.setCompanyId("1");
            dept.setCompanyName("东方教育有限公司");
        } else {
            dept.setCompanyId(((SsCompany) session.getAttribute("company")).getId());
            dept.setCompanyName(((SsCompany) session.getAttribute("company")).getName());
        }
    }

    public <T> List<T> importExcel(MultipartFile file, Class<T> clazz) {
        File tempFile = null;
        try {
            // 创建导入参数
            ImportParams params = new ImportParams();
            // 设置标题行数
            params.setTitleRows(1);
            // 设置表头行数
            params.setHeadRows(1);

            // 转换 MultipartFile 为 File
            tempFile = File.createTempFile("temp", ".xlsx");
            file.transferTo(tempFile);

            // 使用 EasyPoi 导入 Excel
            return ExcelImportUtil.importExcel(tempFile, clazz, params);
        } catch (IOException e) {
            log.error("导入Excel失败：{}", e.getStackTrace());
            return null;
        } finally {
            // 删除临时文件
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();
            }
        }
    }
}
